package org.jsola.hr.web;

import org.apache.commons.lang3.StringUtils;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.PageListUtil;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.CompanyAddDTO;
import org.jsola.hr.dto.CompanyUpdateDTO;
import org.jsola.hr.entity.CompanyDO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.provider.IRecruitProviderService;
import org.jsola.hr.query.CompanyQuery;
import org.jsola.hr.service.ICompanyService;
import org.jsola.hr.service.IGroupCompanyService;
import org.jsola.hr.service.IHrPermissionService;
import org.jsola.hr.vo.CompanyImportExcelVO;
import org.jsola.hr.vo.CompanyListVO;
import org.jsola.hr.vo.CompanyVO;
import org.jsola.recruit2.entity.CompanyUnitsDO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 用工单位
 *
 * @author zhr
 */
@RestController("hrCompanyController")
@RequestMapping(HrConstants.API_PATH + "/v1/companies")
public class CompanyController implements ICompanyControllerAPI {

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IHrPermissionService hrPermissionService;

    @Autowired
    private IGroupCompanyService groupCompanyService;

    @Autowired
    private IRecruitProviderService recruitProviderService;


    @Override
    @PostMapping("/synchronizationCompanyToRecruit")
    public Result<Integer> synchronizationCompanyToRecruit(@RequestBody String[] companyIds) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                companyService.synchronizationCompanyToRecruit(companyIds,tokenUser)
        );
    }

    @Override
    @PostMapping
    public Result<CompanyVO> save(@Valid @RequestBody CompanyAddDTO companyAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增用工单位权限校验

        return Result.success(
                companyService.save(companyAddDTO, tokenUser)
        );
    }

    @Override
    @PostMapping("/import")
    public Result<CompanyImportExcelVO> importFile(@RequestParam("file") MultipartFile file,
                                                   @RequestParam("force") Boolean force) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导入excel权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                companyService.importFile(excelFile, tokenUser, force)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody CompanyUpdateDTO companyUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改用工单位权限校验

//        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), COMPANY_COMPANYMANAGE_EDIT), PERMISSION_DENIED_MESSAGE);

        int count = companyService.update(companyUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{companyId}")
    public Result<Integer> delete(@PathVariable String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除用工单位权限校验

        int count = companyService.deleteByIds(tokenUser, companyId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] companyIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除用工单位权限校验

        int count = companyService.deleteByIds(tokenUser, companyIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }



    @Override
    @GetMapping(value = "/{companyId}")
    public Result<CompanyVO> findById(@PathVariable String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看用工单位权限校验

        return Result.success(
                companyService.selectCompanyInfoByIdASync(companyId, tokenUser)
        );
    }

    @Override
    @GetMapping("/listAllNoSynchronization")
    public Result<Page<CompanyListVO>> listAllNoSynchronization(CompanyQuery companyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        List<CompanyListVO> companyListVOList = companyService.select(companyQuery, tokenUser);
        if(companyQuery.getQueryType()!=null && companyQuery.getQueryType()==1){
            List<CompanyListVO> list = PageListUtil.startPage(companyListVOList, companyQuery.getPageNo(), companyQuery.getPageSize());
            return Result.success(
                    new Page<>(list,companyQuery.getPageNo(), companyQuery.getPageSize(),companyListVOList.size())
            );
        }
        List<CompanyUnitsDO> allCompany = recruitProviderService.getAllCompany(tokenUser);
        Map<String, CompanyListVO> collect = companyListVOList.stream().collect(Collectors.toMap(CompanyListVO::getName, p -> p));
        for (CompanyUnitsDO companyUnitsDO : allCompany) {
            if(collect.containsKey(companyUnitsDO.getName())){
                collect.remove(companyUnitsDO.getName());
            }
        }
        List<CompanyListVO> collect1 = new ArrayList<>(collect.values());
        List<CompanyListVO> list = PageListUtil.startPage(collect1, companyQuery.getPageNo(), companyQuery.getPageSize());

        return Result.success(
                new Page<>(list,companyQuery.getPageNo(), companyQuery.getPageSize(),collect1.size())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<CompanyListVO>> listAll(@Valid CompanyQuery companyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看用工单位权限校验

        return Result.success(
                companyService.select(companyQuery, tokenUser)
        );
    }


    @Override
    @GetMapping
    public Result<Page<CompanyListVO>> page(@Valid CompanyQuery companyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验
        if (!companyQuery.getShowCurrentCompany()
                && StringUtils.isEmpty(companyQuery.getCurrentCompanyId())) {
            return Result.fail("不展示当前公司时,请传递当前公司id");
        }
        return Result.success(
                companyService.selectPage(companyQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/listAllCompany")
    public Result<List<CompanyDO>> selectBySiteId() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                companyService.selectBySiteId(tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listSiteCompany")
    public Result<List<CompanyDO>> listSiteCompany(@RequestParam(value = "siteId") String siteId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                companyService.selectBySiteId(siteId)
        );
    }

    @Override
    @GetMapping(value = "/selectByCostBillId")
    public Result<List<CompanyDO>> selectByCostBillId(@RequestParam(value = "costBillId") Long costBillId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                groupCompanyService.selectCompanyByCostBillId(costBillId, tokenUser)
        );
    }

    @GetMapping(value = "/tileCompanyByUser")
    public Result<List<CompanyDO>> tileCompanyByUser() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                companyService.tileCompanyByUser(tokenUser)
        );
    }
}

